"""
智能决策服务
基于用户偏好和强化学习选择最优服务或工作流
"""

import logging
from typing import Dict, Any
from datetime import datetime

from typing import Dict, Any

from src.services.enhanced_reinforcement_learning_service import get_enhanced_reinforcement_learning_service
from src.services.user_preference_service import get_user_preference_service
from src.research_core.workflow_manager import WorkflowManager
from src.services.service_registry import service_registry

logger = logging.getLogger(__name__)

class IntelligentDecisionService:
    """智能决策服务类"""
    
    def __init__(self):
        """初始化智能决策服务"""
        self.rl_service = get_enhanced_reinforcement_learning_service()
        self.preference_service = get_user_preference_service()
        self.workflow_manager = WorkflowManager()
        
        logger.info("智能决策服务初始化完成")
    
    def select_optimal_workflow(self, user_id: int, question: str, context: Dict[str, Any]) -> str:
        """
        选择最优服务
        
        Args:
            user_id: 用户ID
            question: 用户问题
            context: 上下文信息
            
        Returns:
            str: 选择的服务名称
        """
        try:
            # 提取状态特征
            state_features = self._extract_state_features({
                'question': question,
                'user_id': user_id,
                **context
            })
            
            # 获取用户偏好
            user_preferences = self.preference_service.get_user_preferences(user_id)
            
            # 结合用户偏好调整状态特征
            if user_preferences:
                state_features['user_preference'] = self._analyze_user_preference(user_preferences)
            
            # 使用强化学习选择动作
            action = self.rl_service.get_action(state_features)
            
            # 根据动作选择工作流
            workflow_name = self._map_action_to_workflow(action, question, context)
            
            # 确保返回的服务在服务注册表中存在
            if not service_registry.service_exists(workflow_name):
                logger.warning(f"智能决策选择了不存在的服务: {workflow_name}，回退到默认服务")
                workflow_name = "research_assistant"
            
            logger.debug(f"智能选择工作流: 用户={user_id}, 问题={question[:50]}..., 工作流={workflow_name}")
            return workflow_name
            
        except Exception as e:
            logger.error(f"选择最优工作流失败: {e}")
            # 默认返回研究助理服务（确保返回一个已注册的服务）
            return "research_assistant"
    
    def _analyze_user_preference(self, preferences: Dict[str, Any]) -> str:
        """
        分析用户偏好并生成偏好描述
        
        Args:
            preferences: 用户偏好字典
            
        Returns:
            str: 偏好描述
        """
        if not preferences:
            return "balanced"
        
        # 分析主题偏好
        topic_preferences = {k: v for k, v in preferences.items() if k.startswith('topic_')}
        content_type_preferences = {k: v for k, v in preferences.items() if k.startswith('content_type_')}
        
        # 简单的偏好分类
        if topic_preferences:
            # 找到权重最高的主题
            top_topic = max(topic_preferences.items(), key=lambda x: x[1]['weight'])
            if top_topic[1]['weight'] > 2.0:
                return f"topic_{top_topic[0].replace('topic_', '')}"
        
        if content_type_preferences:
            # 找到权重最高的内容类型
            top_content_type = max(content_type_preferences.items(), key=lambda x: x[1]['weight'])
            if top_content_type[1]['weight'] > 2.0:
                return f"content_{top_content_type[0].replace('content_type_', '')}"
        
        return "balanced"
    
    def _extract_state_features(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        提取状态特征
        
        Args:
            data: 包含问题、用户ID和上下文的字典
            
        Returns:
            Dict[str, Any]: 状态特征字典
        """
        features = {
            'question_length': len(data.get('question', '')),
            'user_id': data.get('user_id', 0),
            'has_context': 1 if data.get('context') else 0,
            'timestamp': datetime.utcnow().timestamp() % 86400  # 当天秒数
        }
        
        # 可以根据需要添加更多特征提取逻辑
        question = data.get('question', '').lower()
        if '优化' in question or '优化' in question:
            features['optimization_related'] = 1
        else:
            features['optimization_related'] = 0
            
        return features
    
    def _map_action_to_workflow(self, action: str, question: str, context: Dict[str, Any]) -> str:
        """
        将动作映射到具体工作流
        
        Args:
            action: 强化学习选择的动作
            question: 用户问题
            context: 上下文信息
            
        Returns:
            str: 工作流名称
        """
        # 根据动作和问题特征选择服务
        if action == "use_realtime_workflow" or "实时" in question or "流" in question:
            # 检查实时助理服务是否存在，如果不存在则回退到研究助理
            if service_registry.service_exists("realtime_assistant"):
                return "realtime_assistant"
            else:
                return "research_assistant"
        else:
            return "research_assistant"
    
    def update_decision_model(self, state: Dict[str, Any], action: str, 
                             result: Dict[str, Any]) -> bool:
        """
        更新决策模型
        
        Args:
            state: 状态
            action: 动作
            result: 执行结果
            
        Returns:
            bool: 是否更新成功
        """
        try:
            # 计算奖励
            reward = self.rl_service.calculate_comprehensive_reward(result)
            
            # 直接使用传入的状态
            state_features = state
            
            # 更新Q值时使用原始action，而不是映射后的action
            self.rl_service.update_q_value(state_features, action, reward, result)
            
            logger.debug(f"决策模型更新: 奖励={reward}")
            return True
            
        except Exception as e:
            logger.error(f"更新决策模型失败: {e}", exc_info=True)
            return False
    
    def _map_workflow_to_action(self, workflow_name: str) -> str:
        """
        将工作流名称映射到动作
        
        Args:
            workflow_name: 工作流名称
            
        Returns:
            str: 动作名称
        """
        workflow_action_mapping = {
            "multi-agent": "use_multi_agent_workflow",
            "optimized-multi-agent": "use_optimized_workflow",
            "streaming-multi-agent": "use_streaming_workflow"
        }
        
        return workflow_action_mapping.get(workflow_name, "use_multi_agent_workflow")
    
    def get_decision_stats(self) -> Dict[str, Any]:
        """
        获取决策统计信息
        
        Returns:
            Dict[str, Any]: 统计信息
        """
        try:
            # 返回空的统计信息，因为EnhancedReinforcementLearningService中没有get_policy_stats方法
            stats = {
                'timestamp': datetime.utcnow().isoformat()
            }
            
            return stats
            
        except Exception as e:
            logger.error(f"获取决策统计失败: {e}")
            return {}


# 全局实例
intelligent_decision_service = IntelligentDecisionService()


def get_intelligent_decision_service():
    """获取智能决策服务实例"""
    return IntelligentDecisionService()